<!--
    by: yuanbiao 2021年12月30日
    name: x-pdf-viewer-mobile
    notes:
-->
<template>
  <div :id="id" :class="[`${prefixCls}`]">
    <canvas ref="canvasItem" v-for="page in pages" :key="page"></canvas>
  </div>
</template>

<script>
const pdfjs = require('pdfjs-dist')
pdfjs.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.min')
const prefixCls = 'x-pdf-viewer-mobile'

export default {
  name: 'x-pdf-viewer-mobile',
  props: {
    options: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      prefixCls: prefixCls,
      id: `xPdfViewerMobile_${Math.random().toString().substring(2)}`,
      page: 1,
      pages: 0,
      pdfDoc: null
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    init() {
      if (this.options.url) {
        this.loadFile(this.options.url)
      }
    },
    loadFile(url) {
      this.loading = true
      pdfjs.getDocument(url).promise.then(pdf => {
        this.pdfDoc = pdf
        this.pages = pdf.numPages
        this.$nextTick(() => {
          this.renderPage(1)
          setTimeout(() => {
            this.loading = false
          }, 1000)
        })
      })
    },
    renderPage(num) {
      this.pdfDoc.getPage(num).then(page => {
        let scale = 2
        let viewport = page.getViewport({ scale: scale })
        // Prepare canvas using PDF page dimensions
        let canvas = this.$refs.canvasItem[num - 1]
        let context = canvas.getContext('2d')
        canvas.height = viewport.height
        canvas.width = viewport.width
        canvas.style.width = '100%'
        // Render PDF page into canvas context
        var renderContext = {
          canvasContext: context,
          viewport: viewport
        }
        page.render(renderContext)
        if (this.pages > num) {
          this.renderPage(num + 1)
        }
      })
    }
  }
}
</script>
